from rest_framework import status, generics, permissions
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth.models import User
from django.db import transaction
from django.db import IntegrityError
from .models import Product, ProductImage, UserProfile, Cart, CartItem, Order, OrderItem
from .serializers import (
    ProductSerializer, UserSerializer, UserProfileSerializer,
    ProductImageSerializer, CartSerializer, CartItemSerializer,
    OrderSerializer
)

# 商品列表和创建 API 接口
class ProductListCreateAPIView(generics.ListCreateAPIView):
    # 只显示状态为'在售'的商品
    queryset = Product.objects.filter(status='在售')
    serializer_class = ProductSerializer
    permission_classes = [permissions.IsAuthenticated]  # 需要登录才能发布商品
    
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        
        # 分页处理
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response({
                "code": 200,
                "data": {
                    "list": serializer.data,
                    "total": queryset.count(),
                    "page": int(request.GET.get('page', 1)),
                    "pageSize": int(request.GET.get('pageSize', 10))
                }
            })

        serializer = self.get_serializer(queryset, many=True)
        return Response({
            "code": 200,
            "data": {
                "list": serializer.data,
                "total": queryset.count(),
                "page": 1,
                "pageSize": queryset.count()
            }
        })
    
    def create(self, request, *args, **kwargs):
        # 设置当前用户为卖家
        request.data['seller'] = request.user.id
        
        # 处理图片上传
        images_data = []
        if 'images' in request.FILES:
            images_data = request.FILES.getlist('images')
        
        # 复制request.data到mutable_data以修改数据
        mutable_data = request.data.copy()
        
        serializer = self.get_serializer(data=mutable_data)
        serializer.is_valid(raise_exception=True)
        
        # 创建商品实例
        product = serializer.save()
        
        # 保存图片
        for image_file in images_data:
            ProductImage.objects.create(product=product, image=image_file)
        
        # 返回前端期望的响应格式
        return Response({
            "code": 200,
            "message": "商品发布成功",
            "data": serializer.data
        }, status=status.HTTP_200_OK)

# 商品详情、更新和删除 API 接口
class ProductRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    permission_classes = []  # 允许匿名访问
    # 查找单个对象时使用的字段，默认为 'pk'
    lookup_field = 'pk'
    
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        
        # 构建符合前端要求的响应格式
        response_data = {
            "code": 200,
            "data": {
                "id": instance.id,
                "title": instance.name,  # 将name映射为title
                "price": float(instance.price),
                "originalPrice": float(instance.original_price) if instance.original_price else None,
                "images": [img.image.url for img in instance.images.all()],
                "description": instance.description,
                "category": instance.category,
                "condition": instance.condition,
                "publishTime": instance.created_at.isoformat(),
                "location": instance.location,
                "status": instance.status,
                "seller": {
                    "id": instance.seller.id,
                    "username": instance.seller.username,
                    "avatar": instance.seller.userprofile.avatar.url if instance.seller.userprofile.avatar else ""
                }
            }
        }
        
        return Response(response_data)


# 购物车API视图
class CartView(generics.RetrieveAPIView):
    serializer_class = CartSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_object(self):
        user = self.request.user
        cart, created = Cart.objects.get_or_create(user=user)
        return cart

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        
        # 构建符合前端要求的响应格式
        return Response({
            "code": 200,
            "data": serializer.data
        })

class CartItemCreateView(generics.CreateAPIView):
    queryset = CartItem.objects.all()
    serializer_class = CartItemSerializer
    permission_classes = [permissions.IsAuthenticated]

    def perform_create(self, serializer):
        user = self.request.user
        cart, created = Cart.objects.get_or_create(user=user)
        product = serializer.validated_data['product']
        
        # 商品数量固定为1，不允许增加数量
        try:
            # 检查商品是否已存在于购物车中
            cart_item, created = CartItem.objects.get_or_create(
                cart=cart,
                product=product,
                defaults={'quantity': 1}
            )
            # 如果商品已存在，不需要增加数量，直接返回已存在的商品
            if not created:
                serializer.instance = cart_item
            else:
                serializer.save(cart=cart)
        except IntegrityError:
            # 如果出现唯一性约束错误，说明商品已经存在，直接返回已存在的商品
            cart_item = CartItem.objects.get(cart=cart, product=product)
            serializer.instance = cart_item

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        
        # 返回标准格式的响应
        return Response({
            "code": 200,
            "message": "商品已成功加入购物车",
            "data": serializer.data
        }, status=status.HTTP_200_OK)


class CartItemUpdateDeleteView(generics.RetrieveUpdateDestroyAPIView):
    queryset = CartItem.objects.all()
    serializer_class = CartItemSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        # 确保用户只能修改自己的购物车商品
        user = self.request.user
        cart = Cart.objects.filter(user=user).first()
        if cart:
            return CartItem.objects.filter(cart=cart)
        return CartItem.objects.none()

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        
        # 返回前端期望的响应格式
        return Response({
            "code": 200,
            "message": "商品删除成功"
        }, status=status.HTTP_200_OK)


# 订单列表视图：获取当前用户的所有订单
class OrderListView(generics.ListAPIView):
    serializer_class = OrderSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return Order.objects.filter(user=self.request.user).order_by('-created_at')

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        
        # 分页处理
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response({
                "code": 200,
                "data": {
                    "list": serializer.data,
                    "total": queryset.count(),
                    "page": int(request.GET.get('page', 1)),
                    "pageSize": int(request.GET.get('pageSize', 10))
                }
            })

        serializer = self.get_serializer(queryset, many=True)
        return Response({
            "code": 200,
            "data": {
                "list": serializer.data,
                "total": queryset.count(),
                "page": 1,
                "pageSize": queryset.count()
            }
        })


# 用户发布的商品列表API视图
class UserProductsListView(generics.ListAPIView):
    serializer_class = ProductSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        # 获取当前用户发布的商品
        return Product.objects.filter(seller=self.request.user).order_by('-created_at')

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        
        # 分页处理
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response({
                "code": 200,
                "data": {
                    "list": serializer.data,
                    "total": queryset.count(),
                    "page": int(request.GET.get('page', 1)),
                    "pageSize": int(request.GET.get('pageSize', 10))
                }
            })

        serializer = self.get_serializer(queryset, many=True)
        return Response({
            "code": 200,
            "data": {
                "list": serializer.data,
                "total": queryset.count(),
                "page": 1,
                "pageSize": queryset.count()
            }
        })


# 创建订单视图：从购物车生成订单
class OrderCreateView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    @transaction.atomic
    def post(self, request, *args, **kwargs):
        user = request.user
        cart, created = Cart.objects.get_or_create(user=user)
        cart_items = cart.items.all()

        if not cart_items:
            return Response({"detail": "购物车为空，无法创建订单。"}, status=status.HTTP_400_BAD_REQUEST)

        # 计算总价时不考虑数量，每个商品只计算一次价格
        total_price = sum(item.product.price for item in cart_items)
        shipping_address = request.data.get('shipping_address')

        if not shipping_address:
            return Response({"detail": "收货地址不能为空。"}, status=status.HTTP_400_BAD_REQUEST)

        order = Order.objects.create(
            user=user,
            total_price=total_price,
            shipping_address=shipping_address,
            status='待付款'
        )

        for item in cart_items:
            OrderItem.objects.create(
                order=order,
                product=item.product,
                quantity=1,  # 固定数量为1，每个商品只能购买一件
                price=item.product.price
            )
            # 将商品状态设为"已售"
            item.product.status = '已售'
            item.product.save()
            # 购买后可以清空购物车中的商品
            item.delete()

        serializer = OrderSerializer(order)
        # 返回前端期望的响应格式
        return Response({
            "code": 200,
            "message": "订单创建成功",
            "data": serializer.data
        }, status=status.HTTP_200_OK)


# 订单详情视图：获取特定订单的详细信息
class OrderDetailView(generics.RetrieveAPIView):
    serializer_class = OrderSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        # 确保用户只能查看自己的订单
        return Order.objects.filter(user=self.request.user)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        
        # 构建符合前端要求的响应格式
        return Response({
            "code": 200,
            "data": serializer.data
        })


# 订单更新视图：更新订单状态
class OrderUpdateView(generics.UpdateAPIView):
    serializer_class = OrderSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        # 确保用户只能更新自己的订单
        return Order.objects.filter(user=self.request.user)

    @transaction.atomic
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        
        # 获取更新前的订单状态
        old_status = instance.status
        
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        # 获取更新后的订单状态
        new_status = instance.status
        
        # 处理订单状态变化对商品状态的影响
        if old_status != new_status:
            # 如果订单状态变为"已付款"
            if new_status == '已付款':
                # 订单支付后，商品状态保持"已售"不变
                pass
            # 如果订单状态变为"已取消"
            elif new_status == '已取消':
                # 取消订单时，将订单内所有商品状态重置为"在售"
                for order_item in instance.items.all():
                    product = order_item.product
                    product.status = '在售'
                    product.save()
            # 如果订单状态变为"已完成"
            elif new_status == '已完成':
                # 订单完成，商品状态保持"已售"不变
                pass

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        # 构建符合前端要求的响应格式
        return Response({
            "code": 200,
            "message": "订单更新成功",
            "data": serializer.data
        })